/*
 * Programmer	:	Muhammad Mohsin Mughal
 * Project	 	:  	Travel Experts Phase 3 (Agent Management)
 * Language  	:  	Java
 * Date Written	:   March 20, 2011.
 * Student Id	:	559933	
 */

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.*;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class TestAgent extends javax.swing.JFrame {
	private JPanel jPanel1;
	private JScrollPane jScrollPane1;
	private JTextField txtAgPos;
	private JTextField txtAgEmail;
	private JTextField txtAgBPhone;
	private JTextField txtAgLName;
	private JTextField txtAgMName;
	private JTextField txtAgFName;
	private JTextField txtAgId;
	private JLabel lblAgAgency;
	private JLabel lblAgPos;
	private JLabel lblAgEmail;
	private JLabel lblAgBPhone;
	private JLabel lblAgMName;
	private JComboBox cbAgentAct;
	private JLabel lblAgAct;
	private JComboBox cbAgencyId;
	private JLabel lblUpdate;
	private JButton btnClear;
	private JButton btnEdit;
	private JButton btnSave;
	private JLabel lblAgLName;
	private JLabel lblAgFName;
	private JLabel lblAgId;
	private JLabel jLabel1;
	private JTable agtTable;
	private Connection conn;
	private Statement stmt;
	private ResultSet rs;
	JDialog d = new JDialog(this, "Dialog box", true);
	private JLabel lblFNameErrMsg;
	DefaultTableModel tblAgentsModel = new DefaultTableModel();
	int updatedrows;
	boolean AddMode = true;

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				TestAgent inst = new TestAgent();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public TestAgent() {
		super();
		initGUI();
		try
		{
			// Generate Tables
			
			loadtable();
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// function to connect to database
	private void databaseConnection()
	{
		try 
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orant11g", "ictoosd", "ictoosd");
			stmt = conn.createStatement();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// function to  fill data in the Agent table
	public void loadtable() throws SQLException
	{
		 while (agtTable.getRowCount() > 0)
		 {
			  ((DefaultTableModel)agtTable.getModel()).removeRow(0);
		 }
		databaseConnection();
		rs = stmt.executeQuery("select * from Agents");
		ResultSetMetaData rsmd = rs.getMetaData();
		String [] header=new String[rsmd.getColumnCount()];
		for(int j=1;j<=rsmd.getColumnCount();j++)
		{
			header[j-1]=rsmd.getColumnLabel(j);
		}
		while(rs.next())
		{
			
			Agents agt = new Agents();
			agt.setagentId(rs.getInt(1));
			agt.setagentFirstName(rs.getString(2));
			agt.setagentMiddleName(rs.getString(3));
			agt.setagentLastName(rs.getString(4));
			agt.setagtBusPhone(rs.getString(5));
			agt.setagentEmail(rs.getString(6));
			agt.setagentPosition(rs.getString(7));
			agt.setagentAgency(rs.getInt(8));
			agt.setagentStatus(rs.getString(9));
			Object [] myAgt = { agt.getagentId(),agt.getagentFirstName(),agt.getagentMiddleName(),
								agt.getagentLastName(),agt.getagtBusPhone(),agt.getagentEmail(),
								agt.getagentPosition(),agt.getagentAgency(),agt.getagentStatus()};
			tblAgentsModel.addRow(myAgt);
			
			
		}
		
		Enumeration<TableColumn> cols = agtTable.getColumnModel().getColumns();
		int i=0;
		while (cols.hasMoreElements())
		{
			TableColumn col = cols.nextElement();
			col.setHeaderValue(header[i++]);
		}
	
		conn.close();
		
	}
	// build the Graphic user interface
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
	
			this.setTitle("Travel Experts");
			{
				jPanel1 = new JPanel();
				getContentPane().add(jPanel1);
				jPanel1.setBounds(0, 0, 784, 545);
				jPanel1.setLayout(null);
				{
					jScrollPane1 = new JScrollPane();
					jPanel1.add(jScrollPane1);
					jScrollPane1.setBounds(18, 29, 743, 189);
					{
						
						agtTable = new JTable();
						jScrollPane1.setViewportView(agtTable);
						agtTable.setModel(tblAgentsModel);
						agtTable.setBounds(25, 46, 597, 87);
						tblAgentsModel.setColumnCount(9);
						agtTable.addKeyListener(new KeyListener() {
							
							@Override
							public void keyTyped(KeyEvent e) {
								// TODO Auto-generated method stub
								
							}
							
							@Override
							public void keyReleased(KeyEvent e) {
								// TODO Auto-generated method stub
								
							}
							
							@Override
							public void keyPressed(KeyEvent e) {
								// TODO Auto-generated method stub
								if(e.getKeyCode()==e.VK_DOWN)
								{
									if(agtTable.getRowCount()>agtTable.getSelectedRow()+1)
									{
										try {
											populateForm(agtTable.getSelectedRow()+1);
										} catch (ParseException e1) {
											// TODO Auto-generated catch block
											e1.printStackTrace();
										}
									}
								}
								else if(e.getKeyCode()==e.VK_UP) 
								{
									if(agtTable.getSelectedRow()==0)
									{
										return;
									}
									if(agtTable.getSelectedRow() <= agtTable.getRowCount()-1)
									{
										try {
											populateForm(agtTable.getSelectedRow()-1);
										} catch (ParseException e1) {
											// TODO Auto-generated catch block
											e1.printStackTrace();
										}
									}
									
								}
								
							}
						});
						// Mouse Clicked Listener
						agtTable.addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) 
							{
								// TODO Auto-generated method stub
								super.mouseClicked(e);
								try {
									populateForm(agtTable.getSelectedRow());
									AddMode = false;
									
								} catch (ParseException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							}
						});
						
					}
				}
			//	Add components to JPanel
				{
					jLabel1 = new JLabel();
					jPanel1.add(jLabel1);
					jLabel1.setText("Agent Maintenance");
					jLabel1.setBounds(148, 0, 294, 23);
					jLabel1.setFont(new java.awt.Font("Abyssinica SIL",1,24));
				}
				{
					lblAgId = new JLabel();
					jPanel1.add(lblAgId);
					lblAgId.setText("Agent Id:");
					lblAgId.setBounds(7, 230, 60, 26);
				}
				{
					lblAgFName = new JLabel();
					jPanel1.add(lblAgFName);
					lblAgFName.setText("Agent First Nm:");
					lblAgFName.setBounds(7, 277, 107, 14);
				}
				{
					lblAgMName = new JLabel();
					jPanel1.add(lblAgMName);
					lblAgMName.setText("Agent Middle Ini:");
					lblAgMName.setBounds(7, 310, 117, 14);
				}
				{
					lblAgLName = new JLabel();
					jPanel1.add(lblAgLName);
					lblAgLName.setText("Agent Last Nm:");
					lblAgLName.setBounds(7, 345, 105, 14);
				}
				{
					lblAgBPhone = new JLabel();
					jPanel1.add(lblAgBPhone);
					lblAgBPhone.setText("Agent Bus Ph:");
					lblAgBPhone.setBounds(7, 380, 105, 14);
				}
				{
					lblAgEmail = new JLabel();
					jPanel1.add(lblAgEmail);
					lblAgEmail.setText("Agent Email:");
					lblAgEmail.setBounds(7, 414, 80, 14);
				}
				{
					lblAgPos = new JLabel();
					jPanel1.add(lblAgPos);
					lblAgPos.setText("Agent Position:");
					lblAgPos.setBounds(7, 440, 105, 14);
				}
				{
					lblAgAgency = new JLabel();
					jPanel1.add(lblAgAgency);
					lblAgAgency.setText("Agent Agency:");
					lblAgAgency.setBounds(481, 307, 88, 14);
				}
				{
					txtAgId = new JTextField();
					jPanel1.add(txtAgId);
					txtAgId.setBounds(156, 233, 284, 21);
					txtAgId.setEnabled(false);
				}
				{
					txtAgFName = new JTextField();
					jPanel1.add(txtAgFName);
					txtAgFName.setBounds(155, 274, 284, 21);
				}
				{
					txtAgMName = new JTextField();
					jPanel1.add(txtAgMName);
					txtAgMName.setBounds(158, 307, 281, 22);
				}
				{
					txtAgLName = new JTextField();
					jPanel1.add(txtAgLName);
					txtAgLName.setBounds(158, 342, 281, 21);
				}
				{
					txtAgBPhone = new JTextField();
					jPanel1.add(txtAgBPhone);
					txtAgBPhone.setBounds(158, 371, 281, 21);
				}
				{
					txtAgEmail = new JTextField();
					jPanel1.add(txtAgEmail);
					txtAgEmail.setBounds(158, 404, 281, 21);
				}
				{
					txtAgPos = new JTextField();
					jPanel1.add(txtAgPos);
					txtAgPos.setBounds(158, 437, 281, 21);
				}
				{
					// Save Button to Add new Records in the Agent Table
					
					btnSave = new JButton();
					jPanel1.add(btnSave);
					btnSave.setText("Add");
					btnSave.setBounds(47, 483, 81, 38);
				//	btnSave.setEnabled(false);
					btnSave.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							System.out.println("btnSave.mouseClicked, event="+evt);
							//TODO add your code for btnSave.mouseClicked
							if ( ! validData())
							{
								
								JOptionPane.showMessageDialog(TestAgent.this, lblFNameErrMsg.getText());
							}
							else if (cbAgentAct.getSelectedItem().equals("Inactive")) {
								
								JOptionPane.showMessageDialog(TestAgent.this, "New Agent Cannot be Inactive");
							}
							else if (! AddMode) {
								
								JOptionPane.showMessageDialog(TestAgent.this, "Record Already Exist");
							}
							else 
								
							{
						
							databaseConnection();
							
						
							String insertSql = "Insert Into AGENTS (AGENTID,AGTFIRSTNAME, AGTMIDDLEINITIAL, AGTLASTNAME, AGTBUSPHONE, AGTEMAIL, AGTPOSITION, AGENCYID,AGENTSTATUS)" 
									+ "Values(S_101_1_AGENTS.nextval, '"+txtAgFName.getText()+"', '"+txtAgMName.getText()+"', '"
									+txtAgLName.getText()+"', '"+txtAgBPhone.getText()+"', '"+txtAgEmail.getText()+"', '"+txtAgPos.getText()+"', "+cbAgencyId.getSelectedItem()+",'"+cbAgentAct.getSelectedItem()+"')";
											
													
							System.out.println("insert button");
							try
							{
								//System.out.println(strSQL);
								stmt.executeUpdate(insertSql);
								loadtable();
								clearFields();
							} 
							catch (SQLException e1) 
							{
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
								
						}
						}

						// validate the data before Entering the record. Make sure all 
						// fields are written 
						private boolean validData() {
							// TODO Auto-generated method stub
							if (txtAgFName.getText().equals(""))
							{
								lblFNameErrMsg = new JLabel("You must Enter First Name ");
								return false;
							}
							else if (txtAgLName.getText().equals(""))
							{
								lblFNameErrMsg = new JLabel("You must Enter Last Name ");
								return false;
							}
							else if (txtAgBPhone.getText().equals(""))
							{
								lblFNameErrMsg = new JLabel("You must Enter Business Phone Numnber ");
								return false;
							}
							else if (txtAgEmail.getText().equals(""))
							{
								lblFNameErrMsg = new JLabel("You must Enter Email of the Agent ");
								return false;
							}
							else if (txtAgPos.getText().equals(""))
							{
								lblFNameErrMsg = new JLabel("You must Enter Agent Position ");
								return false;
							}
							else if (cbAgencyId.getSelectedItem().equals("Select Any Item"))
							{
								lblFNameErrMsg = new JLabel("You must Select Agent Agency ");
								return false;
							}
							else if (cbAgentAct.getSelectedItem().equals("Select Any Item"))
							{
								lblFNameErrMsg = new JLabel("You must Select Agent Status ");
								return false;
							}
							return true;
							
						}
					});
				}
				
				{
					// Clear the fields
					
					btnClear = new JButton();
					jPanel1.add(btnClear);
					btnClear.setText("Clear");
					btnClear.setBounds(408, 482, 85, 40);
					btnClear.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							System.out.println("btnClear.mouseClicked, event="+evt);
							//TODO add your code for btnClear.mouseClicked
							clearFields();
							
							
						}
					});

				}
				// Edit the Agent Record
				{
					btnEdit = new JButton();
					jPanel1.add(btnEdit);
					btnEdit.setBounds(231, 484, 86, 36);
					btnEdit.setText("Edit");
					btnEdit.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							System.out.println("btnEdit.mouseClicked, event="+evt);
							//TODO add your code for btnEdit.mouseClicked
							
							/* if we are change the status of agent to inactive it will allow
							 to assign the customers of this inactive agent to some other 
							 active agent.*/
							// Update Inactive Agent
							if (cbAgentAct.getSelectedItem().equals("Inactive"))
							{
								
								JOptionPane.showMessageDialog(TestAgent.this, "You have to Assign attached customers to other Active Agents");
								CustomerAgtDialog custDlg=new CustomerAgtDialog(TestAgent.this,TestAgent.this.txtAgId.getText());
								custDlg.setModal(true);
								custDlg.setVisible(true);
								txtAgFName.setEnabled(true);
								txtAgMName.setEnabled(true);
								txtAgLName.setEnabled(true);
								txtAgBPhone.setEnabled(true);
								txtAgEmail.setEnabled(true);
								txtAgPos.setEnabled(true);
								btnSave.setEnabled(true);
								databaseConnection();
								String updstr = "update AGENTS set AGTFIRSTNAME ='" +txtAgFName.getText() + "' ,AGTMIDDLEINITIAL='" + txtAgMName.getText()
								+ "' ,AGTLASTNAME='" +txtAgLName.getText()
								+ "' ,AGTBUSPHONE='" +txtAgBPhone.getText()
								+ "' ,AGTEMAIL='" +txtAgEmail.getText()
								+ "' ,AGTPOSITION='" +txtAgPos.getText()
								+ "' ,AGENTSTATUS='" +cbAgentAct.getSelectedItem() 
								+ "' ,AGENCYID='" +cbAgencyId.getSelectedItem()+"'"
								+ "where AGENTID =" + txtAgId.getText();
								try {
									updatedrows = stmt.executeUpdate(updstr);
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (updatedrows > 0)
								{
									lblUpdate.setText("Agent " + txtAgFName.getText() +  " updated successfully");
								}
								// after saving data it enable edit button to edit another agent record and 
								// disable save button and initialize all fields to blank
								
								btnEdit.setEnabled(true);
								//		btnSave.setEnabled(false);
								txtAgId.setText("");
								txtAgFName.setText("");
								txtAgMName.setText("");
								txtAgLName.setText("");
								txtAgBPhone.setText("");
								txtAgEmail.setText("");
								txtAgPos.setText("");
								cbAgentAct.setSelectedIndex(0);
								cbAgencyId.setSelectedIndex(0);
								try {
									loadtable();
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								System.out.println("return to main");
								
								
							}
							else
							{
								// Update Active Agent
								
								txtAgFName.setEnabled(true);
								txtAgMName.setEnabled(true);
								txtAgLName.setEnabled(true);
								txtAgBPhone.setEnabled(true);
								txtAgEmail.setEnabled(true);
								txtAgPos.setEnabled(true);
								//		txtAgAgency.setEnabled(true);
								btnSave.setEnabled(true);
								databaseConnection();
								String updstr = "update AGENTS set AGTFIRSTNAME ='" +txtAgFName.getText() + "' ,AGTMIDDLEINITIAL='" + txtAgMName.getText()
								+ "' ,AGTLASTNAME='" +txtAgLName.getText()
								+ "' ,AGTBUSPHONE='" +txtAgBPhone.getText()
								+ "' ,AGTEMAIL='" +txtAgEmail.getText()
								+ "' ,AGTPOSITION='" +txtAgPos.getText()
								+ "' ,AGENTSTATUS='" +cbAgentAct.getSelectedItem() 
								+ "' ,AGENCYID='" +cbAgencyId.getSelectedItem()+"'"
								+ "where AGENTID =" + txtAgId.getText();
								try {
									updatedrows = stmt.executeUpdate(updstr);
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (updatedrows > 0)
								{
									lblUpdate.setText("Agent " + txtAgFName.getText() +  " updated successfully");
								}
								// after saving data it enable edit button to edit another agent record and 
								// disable save button and initialize all fields to blank
								
								btnEdit.setEnabled(true);
								//		btnSave.setEnabled(false);
								txtAgId.setText("");
								txtAgFName.setText("");
								txtAgMName.setText("");
								txtAgLName.setText("");
								txtAgBPhone.setText("");
								txtAgEmail.setText("");
								txtAgPos.setText("");
								cbAgentAct.setSelectedIndex(0);
								cbAgencyId.setSelectedIndex(0);
								try {
									loadtable();
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					});
				}
				{
					lblUpdate = new JLabel();
					jPanel1.add(lblUpdate);
					lblUpdate.setBounds(481, 411, 241, 17);
				}
				{
					ComboBoxModel cbAgencyIdModel = 
						new DefaultComboBoxModel(getAgencyId());
								
					cbAgencyId = new JComboBox();
					jPanel1.add(cbAgencyId);
					jPanel1.add(getLblAgAct());
					jPanel1.add(getCbAgentAct());
					cbAgencyId.setModel(cbAgencyIdModel);
					cbAgencyId.setBounds(629, 304, 127, 21);
					
				}
			}
			pack();
			this.setSize(774, 568);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	// populate the agencyId ComboBox
	
	private Vector getAgencyId() {
		// TODO Auto-generated method stub
		databaseConnection();
		Vector<String> agency = new Vector<String>();
		
		agency.add("Select Any Item");
		try {
			rs = stmt.executeQuery("select distinct(agencyid) from Agents");
			while (rs.next())
			{
				agency.add(rs.getString("agencyid"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return agency;
	}

	// display columns of selected agent into the text fields
	private void populateForm(int row) throws ParseException 
	{
		// TODO Auto-generated method stub
		
		String [] fields=new String[agtTable.getColumnCount()];
		
		for(int i=0;i<agtTable.getColumnCount();i++)
		{
			fields[i]=""+tblAgentsModel.getValueAt(agtTable.getSelectedRow(), i);
		}
		
			txtAgId.setText(fields[0]);
			txtAgFName.setText(fields[1]);
			txtAgMName.setText(fields[2]);
			txtAgLName.setText(fields[3]);
			txtAgBPhone.setText(fields[4]);
			txtAgEmail.setText(fields[5]);
			txtAgPos.setText(fields[6]);
			cbAgencyId.setSelectedItem(fields[7]);
			cbAgentAct.setSelectedItem(fields[8]);
			
				
		}
	
	public void clearFields()
	{
		txtAgId.setText("");
		txtAgFName.setText("");
		txtAgMName.setText("");
		txtAgLName.setText("");
		txtAgBPhone.setText("");
		txtAgEmail.setText("");
		txtAgPos.setText("");
	//	txtAgAgency.setText("");
		lblUpdate.setText("");
		cbAgencyId.setSelectedIndex(0);
		AddMode = true;
		
		
	}
	
	private JLabel getLblAgAct() {
		if(lblAgAct == null) {
			lblAgAct = new JLabel();
			lblAgAct.setText("Agent Act/DAct");
			lblAgAct.setBounds(481, 277, 106, 14);
		}
		return lblAgAct;
	}
	
	private JComboBox getCbAgentAct() {
		if(cbAgentAct == null) {
			ComboBoxModel cbAgentActModel = 
				new DefaultComboBoxModel(
						new String[] { "Select Any Item","Active", "Inactive" });
			cbAgentAct = new JComboBox();
			cbAgentAct.setModel(cbAgentActModel);
			cbAgentAct.setBounds(629, 271, 127, 21);
		}
		return cbAgentAct;
	}

}
